package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"time"
	"toy/models/cache"
	"toy/models/mysql"

	"toy/toyrpc/internal/svc"
	"toy/toyrpc/toyrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopListLogic {
	return &ShopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopListLogic) ShopList(in *toyrpc.ShopListRequest) (*toyrpc.ShopListResponse, error) {
	// todo: add your logic here and delete this line
	var a []mysql.ShopClassBrand

	key := fmt.Sprintf("list")
	get, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if get != "" {
		json.Unmarshal([]byte(get), &a)
	} else {
		mysql.DB.Table("shops").
			Select("shops.*, classes.name as class_name,brands.name as brand_name").
			Joins("left join classes on classes.id = shops.class_id").
			Joins("left join brands on brands.id = shops.brand_id").
			Find(&a)
		jsonData, _ := json.Marshal(&a)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*1)
	}
	var b []*toyrpc.ShopList
	for _, c := range a {
		list := toyrpc.ShopList{
			Name:      c.Name,
			Price:     float32(c.Price),
			Img:       c.Img,
			ClassName: c.ClassName,
			BrandName: c.BrandName,
		}
		b = append(b, &list)
	}
	return &toyrpc.ShopListResponse{List: b}, nil
}
